<?php

function pr($data = null)
{
    if (!is_null($data)) {
        echo '<pre>';
        print_r($data);
        echo '</pre>';

    }
}

require_once 'Session.php';


class Database
{

    private $isConnected = false;
    private $dbHandle = null;
    private $salt = '329832bgsydft7rt2398r2398tr32vr';
    protected $table = null;

    const DATABASE = 'forecast';
    const DB_USER = 'dev';
    const DB_HOST = 'localhost';
    const DB_PASS = 'dev123';


    public function __construct()
    {
        $this->dbHandle = mysql_connect(self::DB_HOST, self::DB_USER, self::DB_PASS);
        if ($this->dbHandle) {
            mysql_select_db(self::DATABASE);
            $this->isConnected = true;
        }

        $this->init();
    }

    private function init()
    {
        if (isset($_GET['logout'])) {
            Session::dologout();
        }
    }

    public function save($table = null, $data = array())
    {
        $values = $this->prepareValues(array_values($data));

        $sql = "INSERT INTO {$table} (";
        $sql .= implode(",", array_keys($data));
        $sql .= ") VALUES (";
        $sql .= implode(',', $values);
        $sql .= ");";
        mysql_query($sql);

        return mysql_affected_rows() == 1 ? mysql_insert_id() : false;

    }

    private function find($table = null, $field = null, $like = null, $otherParams = null)
    {
        $sql = "SELECT * FROM {$table}";
        if (!is_null($field) && !is_null($like)) {
            $field = mysql_real_escape_string($field);
            $like = mysql_real_escape_string($like);
            $sql .= " WHERE {$field} LIKE '%" . $like . "%'";
        }
        if (!is_null($otherParams)) {
            $sql .= ' ' . $otherParams;
        }
        $resource = mysql_query($sql);
        return is_resource($resource) ? $resource : false;

    }

    public function getTrendAnalysis()
    {
        return $this->find('trendanalysis');
    }

    public function getForecastData()
    {
        return $this->find('forecasttbl');
    }

    public function authenticate($table = null, $data = array())
    {
        if (isset($data['username']) && $data['password']) {

            $username = mysql_real_escape_string($data['username']);
            $password = hash('sha1', $data['password'] . $this->getSalt());
            $password = mysql_real_escape_string($password);
            $sql = "SELECT * FROM {$table} WHERE username = '$username' AND password = '$password' ";
            $query = mysql_query($sql);

            return mysql_affected_rows() == 1 ? mysql_fetch_object($query) : false;
        }
    }

    public function findById($table = null, $id = null)
    {
        $sql = "SELECT * FROM {$table} WHERE id = " . mysql_real_escape_string($id);
        $result = mysql_query($sql);

        return mysql_affected_rows() == 1 ? mysql_fetch_object($result) : false;
    }

    private function prepareValues($array = array())
    {
        $value = array();
        foreach ($array as $key => $val) {
            $prepared = "'" . mysql_real_escape_string($val) . "'";
            array_push($value, $prepared);
        }

        return $value;
    }

    public  function validate($data = null)
    {
        $errors = array();
        if (!is_null($data) && is_array($data)) {
            foreach ($data as $key => $value) {
                if ($value == '') {
                    $errors[$key] = ucfirst(str_replace('_', ' ', $key)) . " cannot be empty";
                }
            }
        }
        return !empty($errors) ? $errors : true;
    }

    public function getGraduatingStudentsByYear($year = null)
    {
        if (!is_null($year) && is_numeric($year)) {
            $query = $this->find('trendanalysis', 'year', $year, 'LIMIT 1');
            if ($query) {
                return mysql_fetch_object($query);
            }
        }
    }

    protected function getSalt()
    {
        return $this->salt;
    }
}
